// SPDX-License-Identifier: GPL-2.0-only
/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 * Author: Huawei OS Kernel Lab
 * Create: Thu Aug 15 16:14:23 2023
 */

#include <linux/export.h>
#include <linux/errno.h>
#include <linux/spinlock.h>
#include <liblinux/pal.h>

#include <trace/hooks/liblinux.h>

static liblinux_mem_hook_t hook_mem_stat;
static DEFINE_RWLOCK(hook_rwlock);

int memstat_enable;
EXPORT_SYMBOL(memstat_enable);

int liblinux_dfx_mem_hook(liblinux_mem_hook_t hook)
{
	write_lock(&hook_rwlock);
	hook_mem_stat = hook;
	write_unlock(&hook_rwlock);
	return 0;
}
EXPORT_SYMBOL(liblinux_dfx_mem_hook);

static void hook_liblinux_mod_memstat(void *__data, enum liblinux_dfx_mem_event ev_enum,
					void *addr, unsigned long size,
					const char *slab_cache_name)
{
	if (hook_mem_stat == NULL)
		return;

	read_lock(&hook_rwlock);
	if (hook_mem_stat != NULL)
		hook_mem_stat((int)ev_enum, addr, size, slab_cache_name);

	read_unlock(&hook_rwlock);
}

static int __init memstat_config(char *str)
{
	if (!str)
		return -EINVAL;

	if (strcmp(str, "on") == 0)
		memstat_enable = 1;
	else
		return -EINVAL;

	return 0;
}
early_param("ldk_memstat", memstat_config);
INIT_VENDOR_HOOK_NOSTOP(ldk_rvh_dfx_call_mem, hook_liblinux_mod_memstat);
